package io.gitee.zicai.bus.config;

import com.google.common.eventbus.AsyncEventBus;
import io.gitee.zicai.bus.bus.Bus;
import io.gitee.zicai.bus.bus.IReceiveBus;
import io.gitee.zicai.bus.bus.ISendBus;
import io.gitee.zicai.bus.core.IBusReceiver;
import io.gitee.zicai.bus.core.IBusSender;
import io.gitee.zicai.bus.listener.IBusReceiveListener;
import io.gitee.zicai.bus.listener.IBusSendListener;
import io.gitee.zicai.bus.publish.IBusPublisher;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * BusCommonConfig
 *
 * @author zicai
 * @since 2021-01-22
 */
@Configuration
@EnableConfigurationProperties(BusCommonProperties.class)
public class BusCommonConfig {

    @Bean
    @ConditionalOnBean(IBusPublisher.class)
    public Bus cmdBus() {
        return new Bus();
    }

    @Bean
    @ConditionalOnMissingBean
    @SuppressWarnings("UnstableApiUsage")
    @ConditionalOnProperty(prefix = BusConst.PREFIX, name = BusConst.TRIGGER_TYPE, havingValue = BusConst.TRIGGER_TYPE_GUAVA)
    public AsyncEventBus asyncEventBus(Executor cmdAsyncPool,
                                       List<IBusSendListener<? extends IBusSender, ? extends ISendBus<?, ?>, ?>> busSendListeners,
                                       List<IBusReceiveListener<? extends IBusReceiver, ? extends IReceiveBus<?, ?>, ?>> busReceiveListeners) {
        AsyncEventBus asyncEventBus = new AsyncEventBus("adaptorAsyncEventBus", cmdAsyncPool);
        busSendListeners.forEach(asyncEventBus::register);
        busReceiveListeners.forEach(asyncEventBus::register);
        return asyncEventBus;
    }

}
